package com.leoman.utils;

import com.leoman.entity.Configue;
import com.leoman.entity.Constant;
import com.leoman.entity.FileBo;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * Created by wangbin on 2014/12/6.
 */
public class FileUtil {

    public static void compactImage(File srcFile, String destDir, String destImage) throws IOException {
        Thumbnails.of(srcFile).scale(1f).outputQuality(0.5).toFile(new File(destDir, destImage));
    }

    public static void thumbImage(File srcFile, String destDir, String destImage, int width, int height) throws IOException {
        BufferedImage srcImage = ImageIO.read(srcFile);
        Thumbnails.of(srcImage)
                .size(width, height)
                .outputQuality(1)
                .keepAspectRatio(false)
                .toFile(new File(destDir, destImage));
    }

    public static Map<String, Long> getImgInfo(String imgPath) {
        File file = new File(imgPath);
        return getImgInfo(file);
    }

    public static Map<String, Long> getImgInfo(File imgFile) {
        Map<String, Long> map = new HashMap<String, Long>(3);
        try {
            FileInputStream fis = new FileInputStream(imgFile);
            BufferedImage buff = ImageIO.read(imgFile);
            map.put("width", buff.getWidth() * 1L);
            map.put("height", buff.getHeight() * 1L);
            map.put("size", imgFile.length());
            fis.close();
        } catch (FileNotFoundException e) {
            System.err.println("所给的图片文件" + imgFile.getPath() + "不存在！计算图片尺寸大小信息失败！");
            map = null;
        } catch (IOException e) {
            System.err.println("计算图片" + imgFile.getPath() + "尺寸大小信息失败！");
            map = null;
        }
        return map;
    }

    /**
     * @param fileIn     要被copy的文件
     * @param fileOutPut 将文件copy到那个目录下面
     * @throws Exception
     */
    public static void copyFile(File fileIn, File fileOutPut) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(fileIn);
        FileOutputStream fileOutputStream = new FileOutputStream(fileOutPut);
        byte[] by = new byte[1024];
        int len;
        while ((len = fileInputStream.read(by)) != -1) {
            fileOutputStream.write(by, 0, len);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }

    public static File fileIsExist(String proId, String salemanId) {
        String path = ConfigUtil.getString("upload.path") + KdxgUtils.getFileName(proId, salemanId);
        File file = new File(path);
        if (file.exists()) {
            return file;
        }
        return null;
    }

    public static String getFileExt(String fileName) {

        int index = fileName.lastIndexOf('.');
        if (index == -1) {
            return "";
        }
        String ext = fileName.substring(index);
        return ext;
    }

    public static boolean isImage(String fileName) {
        return fileName.matches("(?i).+?\\.(jpg|gif|bmp|jpeg|png)");
    }

    public static String readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(file));

            StringBuffer sb = new StringBuffer();

            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                // 对于windows下，\r\n这两个字符在一起时，表示一个换行。
                // 但如果这两个字符分开显示时，会换两次行。
                // 因此，屏蔽掉\r，或者屏蔽\n。否则，将会多出很多空行。
                if (((char) tempchar) != '\r' && ((char) tempchar) != '\n') {
                    sb.append(String.valueOf((char) tempchar));
                }
            }
            reader.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return null;
    }

    public static FileBo save(MultipartFile file, String fileName, Boolean flag, Long size) throws IOException {
        FileBo fileBo = new FileBo();
        Map<String, Object> pathMap = new HashMap<String, Object>();
        InputStream inputStream = file.getInputStream();
        String origFileName = file.getOriginalFilename(); //原始名称,如aa.jpg
        String ext = FileUtil.getFileExt(origFileName); //后缀，如jpg
        String uploadPath = UploadUtil.getImagesUpladPath(); //生成日期目录 image/2014/7/21/
        String foreName = uploadPath + fileName;   //文件名称 image/2014/7/21/221144144554
        String desFilePathName = uploadPath + fileName + ext;//完整文件名称 image/2014/7/21/221144144554.jpg
        File theFile = new File(Configue.getUploadPath(), desFilePathName); //生成的文件对象
        //String webpath = getWebPath(request);

        File dir = theFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileUtils.copyInputStreamToFile(inputStream, theFile);

        if (flag) {
            // 获取图片属性
            BufferedImage imgBufferedImage = ImageIO.read(theFile);
            // 原图宽度
            pathMap.put("imgWidth", imgBufferedImage.getWidth());
            // 原图高度
            pathMap.put("imgHeight", imgBufferedImage.getHeight());
            String suoluepath = UploadUtil.getSuoLueUpladPath() + fileName + ext;
            String suoluepath2 = UploadUtil.getSuoLue2UpladPath() + fileName + ext;
            try {
                BufferedImage bi = null;

                double rate = (double) (size * 1024) / file.getSize();
                bi = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(rate)), (int) (imgBufferedImage.getHeight() * Math.sqrt(rate)));

                File smallfile = new File(Configue.getUploadPath(), suoluepath);
                if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                    smallfile.getParentFile().mkdirs();// 创建上传文件夹
                }
                ImageIO.write(bi, "jpg", smallfile);// 将缩略图写入服务器端的制定文件夹中

                // 缩略图路径
                fileBo.setSuoluePath(suoluepath);

                fileBo.setWidth(bi.getWidth());
                fileBo.setHeight(bi.getHeight());

                /*if (file.getSize() > size *1024) {


                    double rate2 = (double) (size * 1024) / file.getSize();
                    // 当图片大于50K的时候压缩到50K
                    bi2 = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(rate2)), (int) (imgBufferedImage.getHeight() * Math.sqrt(rate2)));
                    File smallfile2 = new File(Configue.getUploadPath(), suoluepath2);
                    if (!smallfile2.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile2.getParentFile().mkdirs();// 创建上传文件夹
                    }
                    ImageIO.write(bi2, "jpg", smallfile2);// 将缩略图写入服务器端的制定文件夹中

                    // 缩略图路径
                    fileBo.setSuoluePath(suoluepath);
                    fileBo.setSuoluePath2(suoluepath2);
                }else if (file.getSize() > 50 *1024 && file.getSize() <= 200 *1024) {
                    double rate = (double) (50 * 1024) / file.getSize();
                    // 当图片大于50K的时候压缩到50K
                    bi2 = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(rate)), (int) (imgBufferedImage.getHeight() * Math.sqrt(rate)));
                    File smallfile2 = new File(Configue.getUploadPath(), suoluepath2);
                    if (!smallfile2.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile2.getParentFile().mkdirs();// 创建上传文件夹
                    }
                    ImageIO.write(bi2, "jpg", smallfile2);// 将缩略图写入服务器端的制定文件夹中

                    // 缩略图路径
                    fileBo.setSuoluePath2(suoluepath2);
                }else {
                    // 当图片小于50K的时候不压缩
                    //bi = FileUtil.resize(theFile, imgBufferedImage.getWidth(), imgBufferedImage.getHeight());// 根据上传的图片文件生成对应的缩略图
                    FileUtils.copyInputStreamToFile(inputStream, theFile);
                }*/
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
        fileBo.setName(fileName);
        fileBo.setForeName(foreName);
        fileBo.setExt(ext);
        fileBo.setPath(desFilePathName);
        fileBo.setFile(theFile);
        return fileBo;
    }

    public static FileBo saveNoThumb(MultipartFile file) throws IOException {
        String fileName = String.valueOf(System.currentTimeMillis());
        FileBo fileBo = new FileBo();
        InputStream inputStream = file.getInputStream();
        String origFileName = file.getOriginalFilename(); //原始名称,如aa.jpg
        String ext = FileUtil.getFileExt(origFileName); //后缀，如jpg
        String uploadPath = UploadUtil.getImagesUpladPath(); //生成日期目录 image/2014/7/21/
        String foreName = uploadPath + fileName;   //文件名称 image/2014/7/21/221144144554
        String desFilePathName = uploadPath + fileName + ext;//完整文件名称 image/2014/7/21/221144144554.jpg
        File theFile = new File(Configue.getUploadPath(), desFilePathName); //生成的文件对象

        File dir = theFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileUtils.copyInputStreamToFile(inputStream, theFile);

        BufferedImage imgBufferedImage = ImageIO.read(theFile);

        fileBo.setPath(desFilePathName);
        fileBo.setSuoluePath(desFilePathName);
        fileBo.setWidth(imgBufferedImage.getWidth());
        fileBo.setHeight(imgBufferedImage.getHeight());
        fileBo.setName(fileName);
        fileBo.setForeName(foreName);
        fileBo.setExt(ext);
        fileBo.setFile(theFile);
        return fileBo;
    }

    public static FileBo save(MultipartFile file, String fileName, Boolean flag) throws IOException {
        int isClose = 0;

        FileBo fileBo = new FileBo();
        Map<String, Object> pathMap = new HashMap<String, Object>();
        InputStream inputStream = file.getInputStream();
        String origFileName = file.getOriginalFilename(); //原始名称,如aa.jpg
        String ext = FileUtil.getFileExt(origFileName); //后缀，如jpg
        String uploadPath = UploadUtil.getImagesUpladPath(); //生成日期目录 image/2014/7/21/
        String foreName = uploadPath + fileName;   //文件名称 image/2014/7/21/221144144554
        String desFilePathName = uploadPath + fileName + ext;//完整文件名称 image/2014/7/21/221144144554.jpg
        File theFile = new File(Configue.getUploadPath(), desFilePathName); //生成的文件对象

        File dir = theFile.getParentFile();
        if (!dir.exists()) {
            dir.mkdirs();
        }

        FileUtils.copyInputStreamToFile(inputStream, theFile);

        fileBo.setPath(desFilePathName);
        fileBo.setSuoluePath(desFilePathName);
        fileBo.setName(fileName);
        fileBo.setForeName(foreName);
        fileBo.setExt(ext);
        fileBo.setFile(theFile);

        if (flag) {
            // 获取图片属性
            BufferedImage imgBufferedImage = ImageIO.read(theFile);
            // 原图宽度
            pathMap.put("imgWidth", imgBufferedImage.getWidth());
            // 原图高度
            pathMap.put("imgHeight", imgBufferedImage.getHeight());
            String suoluepath = UploadUtil.getSuoLueUpladPath() + fileName + ext;
            String suoluepath2 = UploadUtil.getSuoLue2UpladPath() + fileName + ext;

            fileBo.setHeight(imgBufferedImage.getHeight());
            fileBo.setWidth(imgBufferedImage.getWidth());

            BufferedImage bi = null;
            //File smallfile = null;
            //FileInputStream fileInputStream = null;
            BufferedImage bi1 = null;
                /*if (file.getSize() > 300 * 1024) {
                    bi = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(0.8)), (int) (imgBufferedImage.getWidth() * Math.sqrt(0.8)));
                    smallfile = new File(Configue.getUploadPath(), suoluepath);

                    if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile.getParentFile().mkdirs(); // 创建上传文件夹
                    }
                    ImageIO.write(bi, "jpg", smallfile);// 将缩略图写入服务器端的制定文件夹中

                    fileBo.setSuoluePath(suoluepath);
                    fileBo.setWidth(bi.getWidth());
                    fileBo.setHeight(bi.getHeight());

                    fileInputStream = new FileInputStream(smallfile);
                    if (fileInputStream.available() <= 300 * 1024) {
                        fileInputStream.close();
                        isClose = 1;
                    }
                }

                if (isClose == 0) {
                    for (; fileInputStream.available() > 300 * 1024; ) {
                        dealImg(bi, bi, theFile, smallfile, suoluepath, fileBo).close();
                    }
                }*/


            // 验证图片格式
            String originalFileName = file.getOriginalFilename().toLowerCase();
            String fileType = originalFileName.substring(originalFileName.indexOf("."));
            if (file.getSize() > 200 * 1024) {
                if (imgBufferedImage.getWidth() > 1080) {
                    System.out.println("******************************************************图片尺寸超过1080，执行压缩方法一******************************************************");

                    File smallfile = new File(Configue.getUploadPath(), suoluepath);
                    if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile.getParentFile().mkdirs();// 创建上传文件夹
                    }
                    ThumbUtil.format(theFile.getPath(), smallfile.getPath(), 1080, 1080, "jpg");

                    if (fileType.contains(".png")) {
                        suoluepath = suoluepath + ".jpg";
                    }

                    if (imgBufferedImage.getWidth() > imgBufferedImage.getHeight()) {
                        fileBo.setWidth(1080);
                        fileBo.setHeight((int) (1080.0 / imgBufferedImage.getWidth() * imgBufferedImage.getHeight()));
                    } else {
                        fileBo.setHeight(1080);
                        fileBo.setWidth((int) (1080.0 / imgBufferedImage.getHeight() * imgBufferedImage.getWidth()));
                    }

                    // 缩略图路径
                    fileBo.setPath(suoluepath);

                }

                if (imgBufferedImage.getWidth() > 350) {
                    System.out.println("******************************************************图片尺寸超过350，执行压缩方法二******************************************************");

                    File smallfile = new File(Configue.getUploadPath(), suoluepath2);
                    if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile.getParentFile().mkdirs();// 创建上传文件夹
                    }

                    ThumbUtil.format(theFile.getPath(), smallfile.getPath(), 350, 350, "jpg");
                    if (fileType.contains(".png")) {
                        suoluepath2 = suoluepath2 + ".jpg";
                    }

                    // 缩略图路径
                    fileBo.setSuoluePath(suoluepath2);
                }

                /*if (file.getSize() > 200 * 1024) {
                    if (imgBufferedImage.getWidth() > 1080) {
                        System.out.println("******************************************************图片尺寸超过1080，执行压缩方法一******************************************************");

                        bi = FileUtil.resize(theFile, 1080, 1080);
                        File smallfile = new File(Configue.getUploadPath(), suoluepath);
                        if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                            smallfile.getParentFile().mkdirs();// 创建上传文件夹
                        }

                        ImageIO.write(bi, "jpg", smallfile);// 将缩略图写入服务器端的制定文件夹中

                        // 缩略图路径
                        fileBo.setPath(suoluepath);

                    }

                    if (imgBufferedImage.getWidth() > 350) {
                        System.out.println("******************************************************图片尺寸超过350，执行压缩方法二******************************************************");
                        bi1 = FileUtil.resize(theFile, 350, 350);
                        File smallfile = new File(Configue.getUploadPath(), suoluepath2);
                        if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
                            smallfile.getParentFile().mkdirs();// 创建上传文件夹
                        }
                        ImageIO.write(bi1, "jpg", smallfile);// 将缩略图写入服务器端的制定文件夹中

                        // 缩略图路径
                        fileBo.setSuoluePath(suoluepath2);
                    }

                    if (null == bi) {
                        bi = imgBufferedImage;
                    }

                    if (null == bi1) {
                        bi1 = imgBufferedImage;
                    }

                    if (StringUtils.isEmpty(fileBo.getPath()) && StringUtils.isNotEmpty(fileBo.getSuoluePath())) {
                        System.out.println("******************************************************保存图片路径宽高一******************************************************");
                        fileBo.setPath(fileBo.getSuoluePath());
                        fileBo.setWidth(bi1.getWidth());
                        fileBo.setHeight(bi1.getHeight());
                    } else if (StringUtils.isEmpty(fileBo.getSuoluePath())) {
                        System.out.println("******************************************************保存图片路径宽高二******************************************************");
                        fileBo.setPath(desFilePathName);
                        fileBo.setSuoluePath(desFilePathName);
                        fileBo.setWidth(imgBufferedImage.getWidth());
                        fileBo.setHeight(imgBufferedImage.getHeight());
                    }
                }else {
                    fileBo.setPath(desFilePathName);
                    fileBo.setSuoluePath(desFilePathName);
                    fileBo.setWidth(imgBufferedImage.getWidth());
                    fileBo.setHeight(imgBufferedImage.getHeight());
                }*/


                /*if (file.getSize() > size *1024) {


                    double rate2 = (double) (size * 1024) / file.getSize();
                    // 当图片大于50K的时候压缩到50K
                    bi2 = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(rate2)), (int) (imgBufferedImage.getHeight() * Math.sqrt(rate2)));
                    File smallfile2 = new File(Configue.getUploadPath(), suoluepath2);
                    if (!smallfile2.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile2.getParentFile().mkdirs();// 创建上传文件夹
                    }
                    ImageIO.write(bi2, "jpg", smallfile2);// 将缩略图写入服务器端的制定文件夹中

                    // 缩略图路径
                    fileBo.setSuoluePath(suoluepath);
                    fileBo.setSuoluePath2(suoluepath2);
                }else if (file.getSize() > 50 *1024 && file.getSize() <= 200 *1024) {
                    double rate = (double) (50 * 1024) / file.getSize();
                    // 当图片大于50K的时候压缩到50K
                    bi2 = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(rate)), (int) (imgBufferedImage.getHeight() * Math.sqrt(rate)));
                    File smallfile2 = new File(Configue.getUploadPath(), suoluepath2);
                    if (!smallfile2.getParentFile().exists()) {// 如果文件夹不存在
                        smallfile2.getParentFile().mkdirs();// 创建上传文件夹
                    }
                    ImageIO.write(bi2, "jpg", smallfile2);// 将缩略图写入服务器端的制定文件夹中

                    // 缩略图路径
                    fileBo.setSuoluePath2(suoluepath2);
                }else {
                    // 当图片小于50K的时候不压缩
                    //bi = FileUtil.resize(theFile, imgBufferedImage.getWidth(), imgBufferedImage.getHeight());// 根据上传的图片文件生成对应的缩略图
                    FileUtils.copyInputStreamToFile(inputStream, theFile);
                }*/


            }
            //FileUtils.copyInputStreamToFile(inputStream, theFile);
        }
        return fileBo;
    }

    public static FileInputStream dealImg(BufferedImage bi, BufferedImage imgBufferedImage, File theFile, File smallfile, String suoluepath, FileBo fileBo) throws IOException {
        bi = FileUtil.resize(theFile, (int) (imgBufferedImage.getWidth() * Math.sqrt(0.8)), (int) (imgBufferedImage.getWidth() * Math.sqrt(0.8)));
        smallfile = new File(Configue.getUploadPath(), suoluepath);

        if (!smallfile.getParentFile().exists()) {// 如果文件夹不存在
            smallfile.getParentFile().mkdirs(); // 创建上传文件夹
        }
        ImageIO.write(bi, "jpg", smallfile);// 将缩略图写入服务器端的制定文件夹中

        fileBo.setSuoluePath(suoluepath);
        fileBo.setWidth(bi.getWidth());
        fileBo.setHeight(bi.getHeight());

        FileInputStream fileInputStream = new FileInputStream(smallfile);

        return fileInputStream;
    }

    /*public static FileBo save(MultipartFile file, Boolean flag) throws IOException {
        return save(file, String.valueOf(System.currentTimeMillis()), flag, Constant.IMAGE_SIZE_DEFUALT);
    }*/

    public static FileBo save(MultipartFile file, Boolean flag, Long size) throws IOException {
        return save(file, String.valueOf(System.currentTimeMillis()), flag, Constant.IMAGE_SIZE_DEFUALT);
    }

    public static FileBo save(MultipartFile file, Boolean flag) throws IOException {
        return save(file, String.valueOf(System.currentTimeMillis()), flag);
    }

    /**
     * @return BufferedImage 缩放后的图片
     * @Description 等比缩放图片
     * file 源图片,targetW 缩放后的宽度,targetH 缩放后的长度;
     * @date 2014-7-30 下午03:08:52
     * @author 龙哲
     */
    public static BufferedImage resize(File file, int width, int height) {
        try {
            BufferedImage srcImage = ImageIO.read(file);
            if (width > 0 || height > 0) {
                srcImage = getResizedImage(srcImage, width, height);
            }
            return srcImage;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @return BufferedImage 缩放后的图片
     * @Description 缩放图片
     * source 源图片,targetW 缩放后的宽度,targetH 缩放后的长度;
     * @date 2014-7-30 下午03:08:52
     * @author 龙哲
     */
    private static BufferedImage getResizedImage(BufferedImage source, int targetW, int targetH) {
        int type = source.getType();
        BufferedImage target = null;
        // targetW，targetH分别表示目标长和宽
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        //如果目标长度超出现有长度，则返回原图，如果目标长度超出现有长度，则返回原图
        if (targetW >= source.getWidth() || targetH >= source.getHeight()) {
            return source;
        }
        // 这里想实现在targetW，targetH范围内实现等比缩放。如果不需要等比缩放
        // 则将下面的if else语句注释即可
        if (sx > sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        } else {
            sy = sx;
            targetH = (int) (sy * source.getHeight());
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);
        } else {
            target = new BufferedImage(targetW, targetH, type);
        }
        Graphics2D g = target.createGraphics();
        // smoother than exlax:
        g.setColor(Color.WHITE);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
        g.dispose();
        return target;
    }

    /**
     * @return String 时间格式名称
     * @Description 获取项目在tomcat下的地址
     * request request 请求;
     * @date 2014-7-30 下午03:08:52
     * @author 龙哲
     */
    /*public static String getWebPath(ServletRequest request) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession(true);
        String path = session.getServletContext().getRealPath("/").replace(File.separator, "/");
        String[] paths = path.split("/");
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < paths.length - 1; i++) {
            buff.append(paths[i] + "/");
        }
        String newpath = buff.toString();
        return newpath;
    }*/

    /**
     * 压缩文件-由于out要在递归调用外,所以封装一个方法用来
     * 调用ZipFiles(ZipOutputStream out,String path,File... srcFiles)
     *
     * @param zip
     * @param path
     * @param srcFiles
     * @throws IOException
     * @date 2016-9-3 上午09:48:52
     * @author 蔡琦
     */
    public static void ZipFiles(File zip, String path, File... srcFiles) throws IOException {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zip));
        ZipFiles(out, path, srcFiles);
        out.close();
        System.out.println("*****************压缩完毕*******************");
    }

    /**
     * 压缩文件-File
     *
     * @param srcFiles 被压缩源文件
     * @date 2016-9-3 上午09:48:52
     * @author 蔡琦
     */
    public static void ZipFiles(ZipOutputStream out, String path, File... srcFiles) {
        path = path.replaceAll("\\*", "/");
        if (!path.endsWith("/")) {
            path += "/";
        }
        byte[] buf = new byte[1024];
        try {
            for (int i = 0; i < srcFiles.length; i++) {
                if (srcFiles[i].isDirectory()) {
                    File[] files = srcFiles[i].listFiles();
                    String srcPath = srcFiles[i].getName();
                    srcPath = srcPath.replaceAll("\\*", "/");
                    if (!srcPath.endsWith("/")) {
                        srcPath += "/";
                    }
                    out.putNextEntry(new ZipEntry(path + srcPath));
                    ZipFiles(out, path + srcPath, files);
                } else {
                    FileInputStream in = new FileInputStream(srcFiles[i]);
                    System.out.println(path + srcFiles[i].getName());
                    out.putNextEntry(new ZipEntry(path + srcFiles[i].getName()));
                    int len;
                    while ((len = in.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    out.closeEntry();
                    in.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解压到指定目录
     *
     * @param zipPath
     * @param descDir
     * @date 2016-9-3 上午09:48:52
     * @author 蔡琦
     */
    public static void unZipFiles(String zipPath, String descDir) throws IOException {
        unZipFiles(new File(zipPath), descDir);
    }

    /**
     * 解压文件到指定目录
     *
     * @param zipFile
     * @param descDir
     * @date 2016-9-3 上午09:48:52
     * @author 蔡琦
     */
    @SuppressWarnings("rawtypes")
    public static void unZipFiles(File zipFile, String descDir) throws IOException {
        File pathFile = new File(descDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipFile zip = new ZipFile(zipFile);
        for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in = zip.getInputStream(entry);
            String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
            ;
            //判断路径是否存在,不存在则创建文件路径
            File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
            if (!file.exists()) {
                file.mkdirs();
            }
            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if (new File(outPath).isDirectory()) {
                continue;
            }
            //输出文件路径信息
            System.out.println(outPath);

            OutputStream out = new FileOutputStream(outPath);
            byte[] buf1 = new byte[1024];
            int len;
            while ((len = in.read(buf1)) > 0) {
                out.write(buf1, 0, len);
            }
            in.close();
            out.close();
        }
        System.out.println("******************解压完毕********************");
    }

    // 删除文件夹
    // param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除指定文件夹下所有文件
    // param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    public static Map<String, Object> readAndWriteFile(String fileUrl) {
        try {
            Map<String, Object> pathMap;
            File file = new File(Configue.getUploadPath(), fileUrl);
            if (file.exists()) { //判断文件否存
                // 获取图片属性
                BufferedImage imgBufferedImage = ImageIO.read(file);
                pathMap = new HashMap<>();
                pathMap.put("width", imgBufferedImage.getWidth());
                pathMap.put("height", imgBufferedImage.getHeight());
                return pathMap;
            } else {
                System.out.println("找指定文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容错");
            e.printStackTrace();
        }

        return null;

    }

    public static void main(String[] args) throws IOException {
        /**
         * 压缩文件
         */
        /*File[] files = new File[]{new File("F:\\image\\mobile"), new File("F:\\image\\新建文件夹")};
        File zip = new File("F:/压缩.zip");
        ZipFiles(zip, "abc", files);*/

        /**
         * 解压文件
         */
        /*File zipFile = new File("F:/压缩.zip");
        String path = "F:/zipfile/";
        unZipFiles(zipFile, path);*/

        //delAllFile("E:\\server\\tomcat-yqyl\\webapps\\files\\upload\\xml");

        readAndWriteFile("images\\2016\\9\\1475116054314.jpg");
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static String getUrlFromWeb(String url) {
        try {
            byte[] btImg = HttpImageUtil.getImageFromNetByUrl(url);
            if (null != btImg && btImg.length > 0) {
                String timeMillis = String.valueOf(System.currentTimeMillis());
                String desFilePathName = UploadUtil.getImagesUpladPath() + timeMillis + ".jpg";//完整文件名称 image/2014/7/21/221144144554.jpg
                File theFile = new File(Configue.getUploadPath(), desFilePathName); //生成的文件对象

                File dir = theFile.getParentFile();
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileCopyUtils.copy(btImg, theFile);

                return desFilePathName;
            } else {
                System.out.println("没有从该连接获得内容");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
